/*
 * @Author: yangzonglong
 * @Date: 2021-05-17 11:04:43
 * @version: v1.0.0
 * @Descripttion: 选人策略
 * @LastEditors: 871387321@qq.com 871387321@qq.com
 * @LastEditTime: 2023-11-17 09:19:55
 * @Auditor:
 */
import React, { useState, useCallback, useEffect, useRef } from 'react';
import { Form, Select as AntdSelect, Input } from 'antd';
import { Select } from '@library';
import UserInput from '@library/components/formx/extra/UserInput';
import ModalTableInModelInput from '@library/components/formx/extra/ModalTableInModelInput';
import UserProps from '@library/interface/userInfo';
import { getUsers } from './../Api';
import { FormField } from './../../../interface';

const T = window.$app.t;
const FormItem = Form.Item;
const fieldNames = { label: 'codeDesc', value: 'codeValue' };

const userAssignQuery = {
  where: { code: 'WFL_NODE_USERASSIGN_RULE' },
  include: [{ model: 'CompanyCodeValue' }],
};

const rtnDataAfter = (data: any) => {
  return data.CompanyCodeValues;
};

const positionModel = {
  title: '选择岗位',
  url: '/bk/mid/organization/getPositionBeAssgined',
  fieldNames: { label: 'positionName', value: 'positionCode' },
  searchFields: ['positionCode', 'positionName', 'deptName'],
  searchFieldsText: ['岗位编码', '岗位描述', '部门'],
  columns: [
    { title: '岗位编码', dataIndex: 'positionCode' },
    { title: '岗位描述', dataIndex: 'positionName' },
    { title: '部门', dataIndex: 'deptName' },
    {
      title: '用户',
      dataIndex: 'EmployeeAssigns',
      tooltip: true,
      ellipsis: true,
      render: (employeeAssigns: any[]) => {
        return employeeAssigns.map(item => item.userName).join(',')
      }
    }
  ]
}

type DataProps = {
  assignValue?: string | string[];
  assignDesc?: string | string[];
  assignStrategy?: string;
  approvalDistinct?: string;
};

interface IProps {
  onChange?(data: DataProps): void;
  defData?: DataProps;
  vars: FormField[];
  label?: string;
  required?: boolean
}

export default ({ onChange, defData, vars, label, required = true }: IProps) => {
  const isInit = useRef(false);
  const [assignStrategy, setAssignStrategy] = useState(''); // 通知策略
  const [defSlectedUsers, setDefSlectedUsers] = useState<UserProps[]>([]); // 已选择用户
  const [assignDesc, setAssignDesc] = useState<string | string[]>('');
  const [assignValue, setAssignValue] = useState<string | string[]>('');
  const prevAssignStrategy = useRef('');

  useEffect(() => {
    if (defData && !isInit.current) {
      prevAssignStrategy.current = defData.assignStrategy || '';
      setAssignStrategy(defData.assignStrategy || '');
      setAssignValue(defData.assignValue || '');
      setAssignDesc(defData.assignDesc || '');

      if (assignStrategy === 'assignee' && defData.assignValue && Array.isArray(defData.assignValue)) {
        getUsers(defData.assignValue).then((result) => {
          if (result) {
            setDefSlectedUsers(result);
            setAssignDesc(result.map((item) => item.name));
          }
        });
      }
    }
  }, [defData, assignStrategy]);

  useEffect(() => {
    if (onChange) {
      if(prevAssignStrategy.current !== assignStrategy) {
        onChange({ 
          assignValue: [],
          assignDesc: [],
          assignStrategy 
        });
        setAssignValue([]);
        setAssignDesc([]);
        setDefSlectedUsers([]);
        prevAssignStrategy.current = assignStrategy
      }else {
        onChange({ 
          assignValue,
          assignDesc,
          assignStrategy 
        });
      }
    }
  }, [assignValue, assignDesc, assignStrategy, onChange]);

  const changeAssignee = useCallback((value: string, label: string, rows: UserProps[]) => {
    isInit.current = true;

    setAssignValue(rows.map((item) => item.id));
    setAssignDesc(rows.map((item) => item.name));
    setDefSlectedUsers(rows);
  }, []);

  // 改变表单来源
  const changeFormSouce = useCallback((e: any) => {
    isInit.current = true;

    const curr = vars.find(item => item.fieldName === e);
    setAssignValue(e.target ? e.target.value : e)
    setAssignDesc(curr?.name || '')
  }, [vars]);

  // 改变岗位
  const changePosition = useCallback((value: string, id: string, rows: any[]) => {
    isInit.current = true;
    
    setAssignValue(rows.map((item) => item.positionCode));
    setAssignDesc(rows.map((item) => item.positionName));
  }, []);

  return (
    <>
      <Form.Item label={label || T('assignStrategy')} required={required}>
        <Select
          onChange={(e: any) => {
            setAssignStrategy(e.value);
            isInit.current = true;
          }}
          query={userAssignQuery}
          value={assignStrategy}
          fieldNames={fieldNames}
          rtnDataAfter={rtnDataAfter}
          url="/bk/api/company/CompanyCode/findOne"
        />
      </Form.Item>

      {assignStrategy === 'assignee' && (
        <FormItem label={T('designatedUser')} required={required}>
          <UserInput
            extraInitialValue={defSlectedUsers}
            rowSelectionType="checkbox"
            id="assignee"
            value={Array.isArray(assignDesc) ? assignDesc.join(',') : assignDesc}
            onChange={changeAssignee}
          />
        </FormItem>
      )}

      {assignStrategy === 'position' && (
        <FormItem label={T('appointPos')} required={required}>
          <ModalTableInModelInput
            rowSelectionType='radio'
            placeholder={T('positionPlaceholder')}
            id=''
            value={Array.isArray(assignValue) ? assignValue[0] : ''}
            model={positionModel}
            onChange={changePosition} />
        </FormItem>
      )}

      {(assignStrategy === 'formSource' || assignStrategy === 'formSourceEmail') && (
        <FormItem label={T('formSource')} required={required}>
          <AntdSelect
            value={assignValue}
            allowClear
            onChange={changeFormSouce}>
            {vars?.map(item => (
              <AntdSelect.Option value={item.fieldName}>{item.name}</AntdSelect.Option>
            ))}
          </AntdSelect>
        </FormItem>
      )}

      {assignStrategy === 'script' && (
        <Form.Item label={T('script')} required>
          <Input.TextArea 
            onChange={changeFormSouce} 
            rows={8} 
            value={assignValue}/>
        </Form.Item>
      )}
    </>
  );
};
